<template lang="pug">
div
  Form(ref='form', :model='formData', :label-width=80, :rules='rules', action='javascript:;')
    FormItem(label='标题', prop='title')
      Input(v-model='formData.title')
    FormItem(label='媒体文件', prop='media_url')
      div(v-show='!lockUrl')
        Input(v-model='formData.media_url', :disabled='!editable')
      div(v-show='lockUrl')
        oss-uploader(@upload='ossUploaded')
      div(style='margin-top: 3px')
        span 请上传mp4视频或mp3音频。
        a(@click='lockUrl = !lockUrl') {{ lockUrl ? '手动填写地址' : '上传文件' }}

    FormItem(label='时长', prop='media_length')
      Input(v-model='formData.media_length', number, placeholder='媒体播放时长', style='width: 120px')
        span(slot='append') 秒
    FormItem
      Button(type='primary', html-type='submit', @click='add') 添加
      | &nbsp;&nbsp;
      Button(type='ghost', @click='$router.go(-1)') 取消
</template>

<script>
import OSSUploader from '@/components/OSSUploader'
import mediaApi from '@/apis/media'
export default {
  components: {
    'oss-uploader': OSSUploader
  },
  data () {
    return {
      // unit: {}
      lockUrl: true,
      editable: true,
      formData: {
        title: '',
        media_url: '',
        fid: '',
        media_length: 0
      },
      rules: {
        title: { required: true, message: '请填写标题' },
        media_url: { required: true, message: '请填写媒体地址' },
        media_length: { type: 'integer', message: '请填写整数，勿带小数位' }
      }
    }
  },
  mounted () {
    // const { id, delta } = this.$route.params
    // mediaApi.postMediaUnit(id, delta)
    //   .then(unit => (this.unit = unit))
  },
  methods: {
    add () {
      this.$refs.form.validate(valid => {
        console.log('valid', valid)
        if (valid) {
          mediaApi.postMediaUnit(this.$route.params.id, this.formData)
            .then(() => this.$router.replace({
              name: 'media-unit-list',
              params: { id: this.$route.params.id }
            }))
        }
      })
    },
    ossUploaded (res) {
      this.lockUrl = true
      this.editable = false
      this.formData.media_url = 'oss://' + res.name
    }
  }
}
</script>
